/**
 * Created by yiihua-013 on 16/10/26.
 *
 * 统计各个节点平均命中率(stats)
 */
'use strict'

require('json-comments')

const co        = require('co')
const Promise   = require('bluebird')
const Memcached = require('memcached')

const cfg   = require('./memcached')
const nodes = cfg.nodes

var clientsPool = {
    'a':new Memcached(`${nodes['a'].host}:${nodes['a'].port}`),
    'b':new Memcached(`${nodes['b'].host}:${nodes['b'].port}`),
    'c':new Memcached(`${nodes['c'].host}:${nodes['c'].port}`),
    'd':new Memcached(`${nodes['d'].host}:${nodes['d'].port}`),
    'e':new Memcached(`${nodes['e'].host}:${nodes['e'].port}`)
};

var statsAsync = function (client) {
    return new Promise(function (resolve, reject) {
        client.stats((err, stats) => {
            if (err) reject(err);
            var stat = stats[0];
            resolve({server: stat.server, gets: stat.cmd_get, hits: stat.get_hits});
        });
    });
};

exports.stats = function *(next) {

    var totalGets = 0,
        totalHits = 0;

    var promiseArr = [];
    for (let nodeName in nodes) {
        let client = clientsPool[nodeName];
        promiseArr.push(statsAsync(client));
    }

    var ret = co(function *() {
        let results = yield promiseArr;

        results.forEach(result => {
            totalGets += result.gets;
            totalHits += result.hits;
        });

        return {'totalGets': totalGets, 'totalHits': totalHits}
    }).then(ret => ret.totalGets === 0 ? 1 : ret.totalHits / ret.totalGets)
        .catch(function (err) {
            console.trace(err)
        });

    // 初始命中率为100%
    this.body = yield ret;
};
